package com.example.polarity;

import java.util.Random;
import java.util.Vector;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.ViewGroup;

public class ParticleEmitter extends ViewGroup 
{

	Vector<Particle> particles = new Vector<Particle>();
	Matrix matrix = new Matrix();
	Random randomGenerator = new Random();
	Paint paint = new Paint();
	
	int counter = 0;
	
	public ParticleEmitter(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public ParticleEmitter(Context context, AttributeSet attrs)
	{
		super(context,attrs);
		this.setWillNotDraw(false);
		
	}
	
	public ParticleEmitter(Context context, AttributeSet attrs, int defStyle)
	{
		super(context,attrs,defStyle);
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) 
	{
		for(int i = 0; i < 50; i ++)
		{
			int minX = (this.getWidth() / 2) - 20;
			int maxX = (this.getWidth() / 2) - 20;
			int finalX = randomGenerator.nextInt( this.getWidth() - 0) + 0;
			//int finalY = randomGenerator.nextInt( 120 - 70) + 70;
			
			Particle p = new Particle(this.getWidth() / 2, this.getHeight(), 1, 1, Color.GREEN, finalX, 1);
			particles.add(p);
		}
	}

	@Override
	public void onDraw(Canvas canvas)
	{
		
		if(counter == 60)
		{
			for(int i = 0; i < 50; i ++)
			{
				int finalX = randomGenerator.nextInt( this.getWidth() - 0) + 0;
				//int finalY = randomGenerator.nextInt( 120 - 70) + 70;
				
				Particle p = new Particle(this.getWidth() / 2, this.getHeight(), 1, 1, Color.GREEN, finalX, 1);
				particles.add(p);
			}
			counter =0;
		}
		
		for(int i = 0; i < this.particles.size(); i++)
		{
			Particle p = this.particles.get(i);
			
			float dx = p.finalX - p.xPos;
			float dy = p.finalY - p.yPos;
			
			float distSqrd = dx * dx + dy * dy;
			
			float dist = (float) Math.sqrt(distSqrd);
			
			
			dx = dx / dist;
			dy = dy / dist;
			
			
			paint.setColor(p.color);
			p.xPos += dx;
			p.yPos += dy;
			canvas.drawCircle(p.xPos, p.yPos,1, paint);
			
			if(dist < 200)
			{
				this.particles.remove(p);
			}
			
		}
		
		counter++;
		
		invalidate();
	}
	
}
